package com.kpmg.datalake.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.common.constants.Constants;
import com.kpmg.datalake.common.dao.RbacFunctionMapper;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDS;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.enums.RoleTypeEnum;
import com.kpmg.datalake.common.enums.VbaProjectTypeEnum;
import com.kpmg.datalake.common.exception.BusinessException;
import com.kpmg.datalake.common.model.PrvgUsrRole;
import com.kpmg.datalake.common.model.RbacFunction;
import com.kpmg.datalake.common.service.IProjectService;
import com.kpmg.datalake.common.service.IPrvgUsrRoleService;
import com.kpmg.datalake.common.service.IPrvgUsrService;
import com.kpmg.datalake.common.service.RbacFunctionService;
import com.kpmg.datalake.common.thirdparty.kpmgladp.KpmgLadpInterface;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.utils.EncrypUtil;
import com.kpmg.datalake.common.utils.ExceptionUtil;
import com.kpmg.datalake.common.utils.Utils;
import com.kpmg.datalake.common.vo.RbacFunctionVo;
import com.kpmg.datalake.common.vo.RbacRoleVo;
import com.kpmg.datalake.common.vo.RbacUserVo;
import com.kpmg.datalake.common.vo.RbacVo;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.db.model.Project;
import com.kpmg.datalake.db.model.SysUsr;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

/**
 * 权限管理-功能管理
 *
 * @author eguo5
 */
@Service
public class RbacFunctionServiceImpl implements RbacFunctionService {

  private static final Logger logger = LoggerFactory.getLogger(RbacFunctionServiceImpl.class);
  private static final String SMYRCRDID = "SMY_RCRD_ID";
  private static final String UNDERLINE_SEPARATOR = "_";
  private static final String SMYRCRDNM = "SMY_RCRD_NM";

  @Resource
  private RbacFunctionMapper rbacFunctionMapper;
  @Resource
  private IProjectService projectService;
  @Resource
  private IPrvgUsrService prvgUsrService;
  @Resource
  private IPrvgUsrRoleService prvgUsrRoleService;

  /**
   * 对接AD系统
   */
  @Override
  public ServerResponse<JSONObject> getADSystemInfo(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    List<Map<String, Object>> userList;
    try {
      userList = KpmgLadpInterface.searchUser(splitName(rbacVo.getAdSystemInfo()));
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("对接AD系统数据失败,异常:" + e.getMessage());
    }
    result.put("userList", userList);
    return ServerResponse.createBySuccess("对接AD系统数据成功", result);
  }

  public String[] splitName(String name){
    String[] nameInfo=new String[3];
    nameInfo[0]=name;
    if(name.indexOf(",")!=-1){
      nameInfo[1]=name.substring(0,name.indexOf(","));
      nameInfo[2]=name.substring(name.indexOf(",")+1).trim();
      return nameInfo;
    }
    if(name.indexOf(" ")!=-1){
      nameInfo[1]=name.substring(0,name.indexOf(" "));
      nameInfo[2]=name.substring(name.indexOf(" ")+1).trim();
      return nameInfo;
    }
    nameInfo[1]=name;
    nameInfo[2]="";
    return nameInfo;
  }

  /**
   * 获取权限管理功能树
   *
   * @return ServerResponse
   */
  @Override
  public ServerResponse<JSONObject> rbacFunctionTreeJsonObject(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    try {
      if (StringUtils.isEmpty(rbacVo.getProjectId())) {
        rbacVo.setProjectId("");
        Map<String, Object> map = rbacFunctionMapper.getLoginProjectId(rbacVo.getUserId());
        if (map != null && map.get("PROJECTID") != null) {
          rbacVo.setProjectId(map.get("PROJECTID") + "");
        }
      }
      // 原始的数据
      List<RbacFunction> rootFunction = rbacFunctionMapper
          .rbacFunctionTree(rbacVo.getUserId(), rbacVo.getProjectId(),
              ContextHolderUtils.getLocale().toString());
      // 最后的结果
      List<RbacFunction> functionList = new ArrayList<>();
      // 先找到所有的一级功能
      for (RbacFunction aRootFunction : rootFunction) {
        // 一级功能没有parentId
        if (StringUtils.isBlank(aRootFunction.getPrnCd())) {
          functionList.add(aRootFunction);
        }
      }
      // 为一级功能设置子功能，getChild是递归调用的
      for (RbacFunction rbacFunction : functionList) {
        rbacFunction.setChildFunctions(getChild(rbacFunction.getFcnCd(), rootFunction));
      }
      result.put("functionTree", functionList);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("获取功能树失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取功能树成功", result);
  }

  /**
   * 递归查找子功能(通用)
   *
   * @param id id
   * @param rootFunction rootFunction
   * @return List
   */
  private List<RbacFunction> getChild(String id, List<RbacFunction> rootFunction) {
    // 子功能
    List<RbacFunction> childList = new ArrayList<>();
    for (RbacFunction rbacFunction : rootFunction) {
      // 遍历所有节点，将父功能id与传过来的id比较
      if (StringUtils.isNotBlank(rbacFunction.getPrnCd())
          && rbacFunction.getPrnCd().equals(id)) {
        childList.add(rbacFunction);
      }
    }
    // 把子功能的子功能再循环一遍
    for (RbacFunction rbacFunction : childList) {
      // 递归
      rbacFunction.setChildFunctions(getChild(rbacFunction.getFcnCd(), rootFunction));
    } // 递归退出条件
    if (childList.size() == 0) {
      return childList;
    }
    return childList;
  }

  /**
   * 获取权限管理功能树(vba)
   */
  @Override
  public ServerResponse<ArrayList<RbacFunction>> vbaTreeJsonObject() {
    SysUsr user = ContextHolderUtils.getLoginUser();
    String userId = user.getUsrId();
    List<RbacFunction> functionList;
    try {
      // 原始的数据
      List<RbacFunction> rootFunction = rbacFunctionMapper
          .vbaFunctionTree(userId, ContextHolderUtils.getLocale().toString());
      // 最后的结果
      functionList = new ArrayList<>();
      // 先找到所有的一级功能
      for (RbacFunction aRootFunction : rootFunction) {
        // 一级功能没有parentId
        if (StringUtils.isBlank(aRootFunction.getPrnCd())) {
          functionList.add(aRootFunction);
        }
      }
      // 为一级功能设置子功能，getChild是递归调用的
      for (RbacFunction vbaFunction : functionList) {
        vbaFunction.setChildFunctions(
            this.getChildVba(vbaFunction.getFcnCd(), rootFunction, vbaFunction,
                vbaFunction.getUrl()));
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
    return ServerResponse.createBySuccess("获取vba功能树成功", new ArrayList<>(functionList));
  }

  /**
   * 递归查找子功能(vba)
   *
   * @param id id
   * @param rootFunction rootFunction
   * @param vbaFunction vbaFunction
   * @param projectId projectId
   * @return List
   */
  private List<RbacFunction> getChildVba(String id, List<RbacFunction> rootFunction,
      RbacFunction vbaFunction, String projectId) {
    String typeHistory = "1D45C26636C543DB98F39DEE99E64645";
    String typePackage = "1A2C44B04FF3405CBC42F48E63A3F091";
    // 子功能
    List<RbacFunction> childList = new ArrayList<>();
    for (RbacFunction rbacFunction : rootFunction) {
      // 遍历所有节点，将父功能id与传过来的id比较
      if (StringUtils.isNotBlank(rbacFunction.getPrnCd())
          && rbacFunction.getPrnCd().equals(id)) {
        childList.add(rbacFunction);
      }
    }
    // 把子功能的子功能再循环一遍
    for (RbacFunction rbacFunction : childList) {
      // 递归
      rbacFunction.setChildFunctions(
          getChildVba(rbacFunction.getFcnCd(), rootFunction, rbacFunction, projectId));
    } // 递归退出条件
    if (childList.size() == 0) {
      if (typeHistory.equals(vbaFunction.getFcnId())) {
        return this.getVbaHistoryInfo(projectId);
      }
      if (typePackage.equals(vbaFunction.getFcnId())) {
        return this.getRequestList(projectId);
      }
      return childList;
    }
    return childList;
  }

  /**
   * 获取历史报表
   *
   * @param projectId projectId
   * @return List
   */
  public List<RbacFunction> getVbaHistoryInfo(String projectId) {
    SysUsr user = ContextHolderUtils.getLoginUser();
    String userId = user.getUsrId();
    RbacFunctionServiceImpl rbacFunctionServiceImplAOP = (RbacFunctionServiceImpl) AopContext
        .currentProxy();
    // 历史报表下的所有子菜单
    List<RbacFunction> historyReportNodeList = new ArrayList<>();
    List<Map<String, Object>> userTemplateList = rbacFunctionServiceImplAOP
        .getUserRptTemplates(userId, projectId, "");
    if (!userTemplateList.isEmpty()) {
      for (Map<String, Object> templateMap : userTemplateList) {
        String nodeId = projectId + UNDERLINE_SEPARATOR + VbaProjectTypeEnum.QUERY_REPORT.getCode()
            + UNDERLINE_SEPARATOR + String.valueOf(templateMap.get(SMYRCRDID));
        RbacFunction historyTemplateNode = new RbacFunction();
        historyTemplateNode.setUrl(nodeId);
        historyTemplateNode.setFcnNm(String.valueOf(templateMap.get(SMYRCRDNM)));
        historyReportNodeList.add(historyTemplateNode);
      }
    }
    return historyReportNodeList;
  }

  /**
   * 获取vba历史报表信息
   *
   * @return ServerResponse
   */
  @Override
  @DynamicDS("projectId")
  public List<Map<String, Object>> getUserRptTemplates(String userId, String projectId,
      String filter) {
    try {
      return rbacFunctionMapper.vbaTemplateList(userId, filter);
    } catch (Exception e1) {
      logger.error(e1.getMessage());
      return new ArrayList<>();

    }
  }

  public List<RbacFunction> getRequestList(String projectId) {
    List<RbacFunction> childList = new ArrayList<>();
    List<Map<String, Object>> requestList = rbacFunctionMapper
        .selectBySearchForVba(projectId, null, null, "");
    for (Map<String, Object> requestMap : requestList) {
      String childNodeId = projectId + UNDERLINE_SEPARATOR + VbaProjectTypeEnum.PACKAGE.getCode()
          + UNDERLINE_SEPARATOR + requestMap.get("TPL_MGT_ID");
      RbacFunction rbacFunction = new RbacFunction();
      rbacFunction.setUrl(childNodeId);
      rbacFunction.setFcnNm(requestMap.get("TPL_NM") + "");
      childList.add(rbacFunction);
    }
    return childList;
  }

  /**
   * 获取用户所有功能权限列表
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<JSONObject> getRbacFunctions(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    try {
      List<RbacFunction> functionList = rbacFunctionMapper
          .selectFunctionList(rbacVo.getUserId(), rbacVo.getFcnCd(), rbacVo.getFcnNm());
      result.put("functionList", functionList);
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("获取用户所有功能权限列表失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取用户所有功能权限列表成功", result);
  }


  /**
   * 获取DATA用户列表
   *
   * @param rbacVo rbacVo
   * @return List
   */
  @Override
  public ServerResponse<PageInfo<RbacUserVo>> getUserBusiness(RbacVo rbacVo) {
    PageInfo<RbacUserVo> resultPage = null;
    try {
      PageHelper.startPage(rbacVo.getPage(), rbacVo.getSize());
      List<RbacUserVo> userList = rbacFunctionMapper
          .selectUserBusiness(rbacVo.getUserId(), rbacVo.getProjectId());
      PageHelper.clearPage();
      List<Map<String, Object>> roleList = rbacFunctionMapper.selectRoleList();
      for (RbacUserVo rbacUserVo : userList) {
        if (!StringUtils.isEmpty(rbacUserVo.getEmpId())) {
          supplyUserInfo(rbacUserVo);
        }
        rbacUserVo.setEmpAcc(EncrypUtil.decryptAes(rbacUserVo.getEmpAcc(), Constants.ENCRY_KEY));
        rbacUserVo.setRoleSelectList(new ArrayList<>());
        rbacUserVo.getRoleSelectList().addAll(
            rbacFunctionMapper.selectUserRoleType(rbacUserVo.getUsrId(), rbacVo.getProjectId()));
        rbacUserVo.setRoleList(roleList);
      }
      resultPage = new PageInfo<>(userList);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("获取DATA用户列表失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取DATA用户列表成功", resultPage);
  }

  /**
   * 获取数据权限列表
   */
  @Override
  public ServerResponse<JSONObject> getProjectList(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    try {
      List<Map<String, Object>> projectList = rbacFunctionMapper
          .selectProjectList(rbacVo.getUserId());
      result.put("userList", projectList);
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("获取数据权限列表失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取数据权限列表成功", result);
  }

  /**
   * 获取用户权限下角色列表
   *
   * @return ServerResponse
   */
  @Override
  public ServerResponse<JSONObject> getRbacRoleList() {
    JSONObject result = new JSONObject();
    try {
      List<Map<String, Object>> roleList = rbacFunctionMapper.selectRoleList();
      result.put("roleList", roleList);
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("获取角色列表失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取角色列表成功", result);
  }

  /**
   * 添加用户角色关联
   *
   * @param rbacVo rbacVo
   * @return List
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<String> addUserRole(RbacVo rbacVo) {
    try {
      rbacFunctionMapper.deleteUserRole(rbacVo.getUserId(), rbacVo.getProjectId());
      if (rbacVo.getRoleArray().length > 0) {
        rbacFunctionMapper
            .insertUserRole(rbacVo.getUserId(), rbacVo.getUserName(), rbacVo.getRoleArray(),
                rbacVo.getProjectId());
      }
      rbacFunctionMapper.rbacSynchronization(rbacVo.getUserId(), rbacVo.getProjectId());
    } catch (Exception e) {
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ServerResponse.createByErrorMessage("添加用户角色关联失败");
    }
    return ServerResponse.createBySuccessMessage("添加用户角色关联成功");
  }

  /**
   * 新建DATA用户
   *
   * @return ServerResponse
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<JSONObject> addUserForDATA(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    RbacUserVo rbacUserVo = new RbacUserVo();
    String adUserInfoString = rbacVo.getAdUserInfo();
    String[] info = adUserInfoString.split(":");
    String userId = Utils.getGUID();
    if (info.length == 3) {
      rbacUserVo.setEmpAcc(EncrypUtil.encryptAes(info[1], Constants.ENCRY_KEY));
      rbacUserVo.setUsrName(info[1]);
      rbacUserVo.setEmpId(info[0]);
      rbacUserVo.setEmpName(info[2]);
    }
    String empName = rbacUserVo.getEmpName();
    rbacUserVo.setLockSt("0");
    rbacUserVo.setUsrId(userId);
    //用户密码加盐
    rbacUserVo.setSalt(EncrypUtil.generateSalt());
    rbacUserVo.setPassword(EncrypUtil.encryptSha256(info[0] + rbacUserVo.getSalt()));
    try {
      Map<String, Object> mapInfo = isUserExist(info[0]);
      if (mapInfo.isEmpty()) {
        rbacFunctionMapper.insertUserInfoOld(rbacUserVo);
      } else {
        userId = mapInfo.get("USR_ID") + "";
      }
      rbacFunctionMapper
          .insertUserRole(userId, empName, new String[]{"40BCFA4EF3F6415B9A18FBD91B60593A"},
              rbacVo.getProjectId());
      rbacFunctionMapper.rbacSynchronization(userId, null);
      rbacUserVo.setUsrId(userId);
      supplyUserInfo(rbacUserVo);
      rbacUserVo.setEmpAcc(info[1]);
      rbacUserVo.setRoleList(rbacFunctionMapper.selectRoleList());
      rbacUserVo.setRoleSelectList(new ArrayList<>());
      rbacUserVo.getRoleSelectList().addAll(
          rbacFunctionMapper.selectUserRoleType(rbacUserVo.getUsrId(), rbacVo.getProjectId()));
      result.put("newUser", rbacUserVo);
    } catch (Exception e) {
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("新建DATA用户失败");
    }
    return ServerResponse.createBySuccess("新建DATA用户成功", result);
  }

  /**
   * 根据projectid和its_code进行权限同步
   */
  @Override
  public ServerResponse<String> rbacSynchronization() {
    try {
      rbacFunctionMapper.rbacSynchronization(null, null);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorCodeMessage(ResultCodeEnum.CODE4030.getCode(),
          ResultCodeEnum.CODE4030.getDisplay());
    }
    return ServerResponse.createBySuccess();
  }

  /**
   * 删除DATA用户
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> deleteUserForDATA(RbacVo rbacVo) {
    try {
      rbacFunctionMapper.deleteUserForDATA(rbacVo.getUserId(), rbacVo.getProjectId());
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("删除DATA用户失败");
    }
    return ServerResponse.createBySuccessMessage("删除DATA用户成功");
  }

  /**
   * 从AD系统补充用户信息
   */
  private void supplyUserInfo(RbacUserVo rbacUserVo) throws Exception {
    rbacUserVo.setEmail(KpmgLadpInterface.searchUserEmail(rbacUserVo.getEmpId()));
  }

  /**
   * 判断用户是否已存在
   */
  public Map<String, Object> isUserExist(String empId) {
    Map<String, Object> map = new HashMap<>();
    try {
      List<Map<String, Object>> list = rbacFunctionMapper.selectUserByEmpId(empId);
      if (!list.isEmpty()) {
        map = list.get(0);
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return map;
    }
    return map;
  }

  /**
   * 修改密码
   */
  @Override
  public ServerResponse<String> changePassword(RbacVo rbacVo) {
    try {
      Map<String, Object> map = rbacFunctionMapper.selectUserByUserId(rbacVo.getUserId());
      if (!EncrypUtil.encryptSha256(rbacVo.getPassword()).equals(map.get("USR_PWD") + "")) {
        return ServerResponse.createByErrorMessage("原密码输入错误");
      }
      rbacFunctionMapper
          .changePassword(rbacVo.getUserId(), EncrypUtil.encryptSha256(rbacVo.getNewPassword()));
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("密码修改失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccessMessage("密码修改成功");
  }

  /**
   * 获取BA用户列表
   */
  @Override
  public ServerResponse<PageInfo<RbacUserVo>> getUserForBA(RbacVo rbacVo) {
    PageInfo<RbacUserVo> resultPage = null;
    try {
      PageHelper.startPage(rbacVo.getPage(), rbacVo.getSize());
      List<RbacUserVo> userList = rbacFunctionMapper.selectUserBA(RoleTypeEnum.BA.getCode());
      for (RbacUserVo rbacUserVo : userList) {
        if (!StringUtils.isEmpty(rbacUserVo.getEmpId())) {
          supplyUserInfo(rbacUserVo);
        }
        rbacUserVo.setEmpAcc(EncrypUtil.decryptAes(rbacUserVo.getEmpAcc(), Constants.ENCRY_KEY));
        rbacUserVo.setRoleSelectList(new ArrayList<>());
        rbacUserVo.getRoleSelectList().add(RoleTypeEnum.BA.getCode());
      }
      resultPage = new PageInfo<>(userList);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("获取BA用户列表失败,异常:" + e.getMessage());
    }
    return ServerResponse.createBySuccess("获取BA用户列表成功", resultPage);
  }

  /**
   * 新建BA用户
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<JSONObject> addUserForBA(RbacVo rbacVo) {
    JSONObject result = new JSONObject();
    String userId = Utils.getGUID();
    String adUserInfoString = rbacVo.getAdUserInfo();
    RbacUserVo rbacUserVo = new RbacUserVo();
    String[] info = adUserInfoString.split(":");
    if (info.length == 3) {
      rbacUserVo.setEmpName(info[2]);
      rbacUserVo.setEmpAcc(EncrypUtil.encryptAes(info[1], Constants.ENCRY_KEY));
      rbacUserVo.setUsrName(info[1]);
      rbacUserVo.setEmpId(info[0]);
    }
    //用户密码加盐
    rbacUserVo.setSalt(EncrypUtil.generateSalt());
    rbacUserVo.setPassword(EncrypUtil.encryptSha256(info[0] + rbacUserVo.getSalt()));
    String empName = rbacUserVo.getEmpName();
    rbacUserVo.setUsrId(userId);
    rbacUserVo.setLockSt("0");
    try {
      Map<String, Object> map = isUserExist(info[0]);
      if (map.isEmpty()) {
        rbacFunctionMapper.insertUserInfoOld(rbacUserVo);
      } else {
        userId = map.get("USR_ID") + "";
      }
      rbacFunctionMapper
          .insertUserRole(userId, empName, new String[]{"49897C6334E34DA49A71DEEEC4089037"}, "");
      rbacUserVo.setUsrId(userId);
      supplyUserInfo(rbacUserVo);
      rbacUserVo.setEmpAcc(info[1]);
      rbacUserVo.setRoleSelectList(new ArrayList<>());
      rbacUserVo.getRoleSelectList().add(RoleTypeEnum.BA.getCode());
      result.put("newUser", rbacUserVo);
    } catch (Exception e) {
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      logger.error(e.getMessage());
      return ServerResponse.createByErrorMessage("新建BA用户失败");
    }

    return ServerResponse.createBySuccess("新建BA用户成功", result);
  }

  /**
   * 删除BA用户
   */
  @Override
  public ServerResponse<String> deleteUserForBA(RbacVo rbacVo) {
    try {
      rbacFunctionMapper.deleteUserForBA(rbacVo.getUserId());
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("删除BA用户失败");
    }

    return ServerResponse.createBySuccessMessage("删除BA用户成功");
  }

  /**
   * 获取所有project
   */
  @Override
  public ServerResponse<JSONObject> getAllProject() {
    JSONObject result = new JSONObject();
    try {
      result.put("projectList", rbacFunctionMapper.getAllProject());
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage("获取全部project列表失败");
    }
    return ServerResponse.createBySuccess("获取全部project列表成功", result);
  }

  /**
   * 新建角色
   *
   * @param rbacRoleVo rbacRoleVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> addRole(RbacRoleVo rbacRoleVo) {
    rbacRoleVo.setRlId(Utils.getGUID());
    rbacRoleVo.setDelId("1");
    rbacRoleVo.setStatus("1");
    rbacFunctionMapper.insertRoleInfo(rbacRoleVo);
    return ServerResponse.createBySuccessMessage("新建角色成功");
  }

  /**
   * 新建功能
   *
   * @param rbacFunctionVo rbacFunctionVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> addFunction(RbacFunctionVo rbacFunctionVo) {
    rbacFunctionVo.setFcnid(Utils.getGUID());
    rbacFunctionVo.setDelid("1");
    rbacFunctionVo.setStatus("1");
    rbacFunctionMapper.insertFunctionInfo(rbacFunctionVo);
    return ServerResponse.createBySuccessMessage("新建功能成功");
  }

  /**
   * 用户状态更新(1:启用;0:禁用)
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> updateUserStatus(RbacVo rbacVo) {
    rbacFunctionMapper.updateUserStatusByUserId(rbacVo.getUserId(), rbacVo.getStatus());
    return ServerResponse.createBySuccessMessage("修改用户状态成功");
  }


  /**
   * 角色状态更新(1:启用;0:禁用)
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> updateRoleStatus(RbacVo rbacVo) {
    rbacFunctionMapper.updateRoleStatusByRoleId(rbacVo.getRoleId(), rbacVo.getStatus());
    return ServerResponse.createBySuccessMessage("修改角色状态成功");
  }

  /**
   * 删除角色
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  public ServerResponse<String> deleteRoleStatus(RbacVo rbacVo) {
    rbacFunctionMapper.deleteRoleStatusByRoleId(rbacVo.getRoleId(), rbacVo.getDelSign());
    return ServerResponse.createBySuccessMessage("删除角色成功");
  }

  /**
   * 用户添加角色
   *
   * @param rbacVo rbacVo
   * @return ServerResponse
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<String> userAddRole(RbacVo rbacVo) {
    try {
      rbacFunctionMapper.userDeleteRoleByUserId(rbacVo);
      rbacFunctionMapper.userAddRole(rbacVo);
    } catch (Exception e) {
      logger.error(e.getMessage());
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return ServerResponse.createByErrorMessage("用户角色权限修改失败");
    }
    return ServerResponse.createBySuccessMessage("用户角色权限修改成功");
  }

  /**
   * 同步项目用户信息权限
   *
   * @param project 项目信息U
   * @return 执行结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<String> syncProjectUserPermissions(Project project) {
    if (project == null) {
      throw new BusinessException(ResultCodeEnum.CODE4000, "项目信息不能为空");
    }
    if (StringUtils.isBlank(project.getPrjId())) {
      throw new BusinessException(ResultCodeEnum.CODE4000, "项目ID不能为空");
    }
    Project oldProject = projectService.selectById(project.getPrjId());
    //如果新增项目不存在 为了老数据穿空
    if (oldProject == null) {
      oldProject = new Project();
    }
    RbacFunctionServiceImpl currentProxy = ((RbacFunctionServiceImpl) AopContext.currentProxy());
    //dataOwner
    currentProxy.handleUserPermissions(project.getPrjDataOwner(), oldProject.getPrjDataOwner(),
        project.getEntityBasic().getEntNm(),
        RoleTypeEnum.DataOwner, project.getPrjId());
    //DataManager
    currentProxy.handleUserPermissions(project.getPrjManager(), oldProject.getPrjManager(),
        project.getEntityBasic().getEntNm(),
        RoleTypeEnum.DataManager, project.getPrjId());
    //Delegator
    currentProxy.handleUserPermissions(project.getPrjDeleGator(), oldProject.getPrjDeleGator(),
        project.getEntityBasic().getEntNm(),
        RoleTypeEnum.Delegator, project.getPrjId());
    return ServerResponse.createBySuccess();
  }

  @Override
  public List<String> queryProjectPrivilegeIdList(String userId) {
    List<Map<String, Object>> projectList = rbacFunctionMapper
        .selectProjectList(userId);

    List<String> projectIdList = new ArrayList<>();

    // 查询用户数据权限列表
    for (Map<String, Object> item : projectList) {
      projectIdList.add(item.get("ID").toString());
    }
    return projectIdList;
  }

  /**
   * 处理用户权限信息
   *
   * @param newUserName 新用户
   * @param oldUserName 老用户
   * @param roleType 用户类型
   * @param projectId 用户ID
   */
  @Transactional(rollbackFor = Exception.class)
  public void handleUserPermissions(String newUserName, String oldUserName, String entNm,
      RoleTypeEnum roleType,
      String projectId) {
    if (Objects.equals(newUserName, oldUserName)) {
      return;
    }
    if (StringUtils.isBlank(newUserName)) {
      //老用户权限
      List<String> oldUserPermissions = prvgUsrRoleService
          .getOldUserPermissions(oldUserName, projectId, roleType.getCode());
      if (!CollectionUtils.isEmpty(oldUserPermissions)) {
        prvgUsrRoleService.deleteBatchIds(oldUserPermissions);
      }
    } else {
      SysUsr sysUsr = prvgUsrService.autoCheckAndCreate(newUserName);
      if (sysUsr == null) {
        return;
      }
      //如果原来用户不存在，则新用户新增
      if (StringUtils.isBlank(oldUserName)) {
        prvgUsrRoleService
            .saveNewUserPermissions(newUserName, projectId, entNm, roleType.getCode());
        return;
      }
      //老用户权限
      List<String> oldUserPermissions = prvgUsrRoleService
          .getOldUserPermissions(oldUserName, projectId, roleType.getCode());
      //如果老用户权限不存在 则直接新增
      if (CollectionUtils.isEmpty(oldUserPermissions)) {
        prvgUsrRoleService
            .saveNewUserPermissions(newUserName, projectId, entNm, roleType.getCode());
        return;
      }
      //如果老用户权限存在，则权限修改
      List<PrvgUsrRole> prvgUsrRoleList = new ArrayList<>();
      for (String oldPermissions : oldUserPermissions) {
        PrvgUsrRole usrRole = new PrvgUsrRole();
        usrRole.setId(oldPermissions);
        usrRole.setUsrid(sysUsr.getUsrId());
        usrRole.setUsrnm(sysUsr.getUsrNmEn());
        prvgUsrRoleList.add(usrRole);
      }
      if (!CollectionUtils.isEmpty(prvgUsrRoleList)) {
        prvgUsrRoleService.updateBatchById(prvgUsrRoleList);
      }
    }


  }

}
